import sqlite3, time
from CoreFunctions import GetConfig, GetSetting

class DatabaseUtilities():
    def __init__(self):
        self.DBName         = ""
        self.MovieFolder    = ""
        self.MovieTypes     = []
        self.Mode           = 1     #update mode
        self.OSSeperator    = "/"
        self.DoLog          = True
        self.LogMode        = 'a'
           
        if GetConfig('settings.ini'):
            self.DBName         = GetSetting("Common", "DBName")         #"/Movies/Python/MovieDB.db"
            self.OSSeperator    = GetSetting("Common", "OSSeperator")    
            self.LogFile        = GetSetting("Common", "LogFile")
            self.ThumbsFolder   = GetSetting("MovieDatabase", "ThumbsFolder")
        self.cn = sqlite3.connect(self.DBName)
    def DownLoadActorThumbs(self):
        import urllib, os
        SQL = "SELECT ActorThumb from tblActors"
        self.cursor = self.cn.execute(SQL)
        rows = self.cursor.fetchall()
        if rows:
            for row in rows:
                try:
                    if row[0]!=None:
                        thumb=self.ThumbsFolder + self.OSSeperator + row[0].split("/")[-1:][0]
                        if os.path.exists(self.ThumbsFolder + self.OSSeperator + thumb)==False:
                            
                            urllib.urlretrieve(row[0], thumb )
                            print "Retrieved Thumb " + row[0]
                except Exception, x:
                    print("Error downloading thumbnail" + row[0] )   
                    print x
    def UpdateGenres(self):
        SQL = "SELECT Genre from tblMovies"
        try:
            self.cursor = self.cn.execute(SQL)
            rows = self.cursor.fetchall()
            if rows:
                for row in rows:
                    genres = row[0].split("/")
                    #genres = genres
                    if len(genres) > 0:
                        for genre in genres:
                            if genre>"":
                                try:
                                    
                                    SQL = "INSERT INTO tblGenres (Genre) VALUES ('%s')" % genre.replace(" ", "")
                                    self.cursor = self.cn.execute(SQL)
                                except Exception, x:
                                    self.LogEvent(x)
                                finally:
                                    self.cn.commit()  
                              
        except Exception, x:
            self.LogEvent(x)
            return False
        
    def AddColumn(self, Table, Column, Specs):
        try:
            SQL = "ALTER TABLE '%s' ADD '%s' '%s'" % (Table, Column, Specs)
            self.LogEvent(SQL)
            self.cursor = self.cn.execute(SQL)
            self.cursor = None
            return True
        except Exception, x:
            self.LogEvent(x)
            return False
    
    def LogEvents(self, LogEvents, Mode):
        self.DoLog = False
        if LogEvents==True:
            self.DoLog = True
            self.LogMode = Mode 
            
    
    def LogEvent(self, EventText):         
        if self.DoLog == True:
            self.EventLog = open(self.LogFile, self.LogMode)
            self.EventLog.write(time.strftime('[%H:%M:%S] ', time.localtime()))
            self.EventLog.write(unicode(EventText) + "\n")
            self.EventLog.close()    
        
if __name__=="__main__":
    Utils = DatabaseUtilities()
    #print "Ading column 'VideoOutput' to table 'tblMovies'"
    #print Utils.AddColumn("tblMovies", "VideoOutput", "text DEFAULT NULL")
    Utils.UpdateGenres()   
    Utils.DownLoadActorThumbs() 